package com.nami.store.biz.group.repository.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nami.store.api.response.group.GroupDTO;
import com.nami.store.biz.group.convert.GroupConvert;
import com.nami.store.domain.GroupDO;
import com.nami.store.mapper.GroupMapper;
import com.nami.store.biz.group.repository.GroupRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 群信息 服务实现类
 * </p>
 *
 * @author lbc
 * @since 2023-08-17
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class GroupServiceImpl implements GroupRepository {

    private final GroupMapper baseMapper;


    @Override
    public List<GroupDTO> getGroups(List<String> groupIds) {
        if (CollUtil.isEmpty(groupIds)) {
            return null;
        }

        List<GroupDO> list = baseMapper.selectList(new LambdaQueryWrapper<GroupDO>().in(GroupDO::getGroupId, groupIds));
        return GroupConvert.INSTANCE.convertList(list);
    }

    @Override
    public Map<String, GroupDTO> getGroupMap(List<String> groupIds) {
        if (CollUtil.isEmpty(groupIds)) {
            return new HashMap<>();
        }

        List<GroupDTO> groups = this.getGroups(groupIds);
        if (CollUtil.isEmpty(groups)) {
            return new HashMap<>();
        }

        return groups.stream().collect(Collectors.toMap(GroupDTO::getGroupId, Function.identity()));
    }

    @Override
    public Map<String, GroupDTO> getGroupsByGroupIds(List<String> groupIds) {
        List<GroupDTO> groups = this.getGroups(groupIds);
        if (CollUtil.isEmpty(groups)) {
            return new HashMap<>();
        }
        Map<String, GroupDTO> result = groups.stream().collect(Collectors.toMap(key -> key.getId() + "", Function.identity()));

        return result;
    }

    @Override
    public GroupDO getGroup(String groupId) {
       GroupDO exist =  baseMapper.selectOne(new LambdaQueryWrapper<GroupDO>().eq(GroupDO::getGroupId, groupId));
        return exist;
    }

    @Override
    public GroupDO getGrpInfo(String appKey, String grpId) {
        if (StringUtils.isBlank(grpId) || StringUtils.isBlank(appKey)) {
            return null;
        }

        return baseMapper.selectOne(new LambdaQueryWrapper<GroupDO>()
            .eq(GroupDO::getAppKey, appKey)
            .eq(GroupDO::getGroupId, grpId));
    }

}
